package com.example.myapplication.markwon

import android.graphics.Color
import android.text.Spannable
import android.text.TextPaint
import android.text.style.URLSpan
import android.util.Log
import android.view.View
import android.widget.TextView
import io.noties.markwon.LinkResolver
import io.noties.markwon.core.MarkwonTheme

/**
 * Create by Tanzhenxing on 2025/7/14.
 * Description:
 */
class LinkSpan(
    private val theme: MarkwonTheme,
    private val linkString: String,
    private val resolver: LinkResolver
) : URLSpan(linkString) {

    private var isClicked = false
    override fun onClick(widget: View) {
        if (!isClicked) {
            isClicked = true
            (widget as? TextView)?.let { textView ->
                val content = textView.text
                textView.text = content
            }
        }
        resolver.resolve(widget, linkString)
        ((widget as? TextView)?.text as? Spannable)?.let { spannable ->
            // val urlSpans = spannable.getSpans(0, spannable.length, URLSpan::class.java)
            // // 遍历所有的 URLSpan，获取每个超链接的文案
            // urlSpans.forEach { urlSpan ->
            //     // 获取 URLSpan 对应的超链接 URL
            //     val url = urlSpan.url
            //     // 获取 URLSpan 所在的文本区间
            //     val start = spannable.getSpanStart(urlSpan);
            //     val end = spannable.getSpanEnd(urlSpan);
            //     // 获取超链接文本（即超链接对应的文案）
            //     val linkText = spannable.subSequence(start, end).toString();
            //     // 输出结果
            //     Log.d("URLSpan", "URL: $url, Link Text: $linkText");
            // }
            val start = spannable.getSpanStart(this@LinkSpan)
            val end = spannable.getSpanEnd(this@LinkSpan)
            // 获取超链接文本（即超链接对应的文案）
            val linkText = spannable.subSequence(start, end).toString();
            // 输出结果
            Log.d("URLSpan", "URL: $url, Link Text: $linkText");
        }
    }

    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)
        theme.applyLinkStyle(ds)
        if (isClicked) {
            ds.color = Color.GREEN
        }
    }

}